package com.luboyan.CBillbill.service.file.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.luboyan.CBillbill.mapper.file.FileMapper;
import com.luboyan.CBillbill.dao.file.File;
import com.luboyan.CBillbill.service.file.FileService;
import com.luboyan.CBillbill.util.FastDFSUtil;
import com.luboyan.CBillbill.util.encrypt.MD5Util;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

@Service
public class FileServiceImpl implements FileService{

    @Autowired
    private FileMapper fileMapper;

    @Autowired
    private FastDFSUtil fastDFSUtil;

    /**
     * 分片上传文件
     */
    @Override
    public HashMap<String, String> uploadFileByShard(MultipartFile file, String fileMd5, Integer shard, Integer shardTotal) throws Exception{
        HashMap<String, String> result = new HashMap<>();
        //秒传实现
        QueryWrapper<File> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("md5", fileMd5);
        File dbFile = fileMapper.selectOne(queryWrapper);
        if(dbFile != null){
            result.put("秒传",dbFile.getUrl());
//            return dbFile.getUrl();
            return result;
        }

        String url = fastDFSUtil.uploadFileByShard(file, fileMd5, shard, shardTotal);
        if(!StringUtils.isNullOrEmpty(url)){
            dbFile = new File();
            dbFile.setCreateTime(new Date());
            dbFile.setUrl(url);
            dbFile.setMd5(fileMd5);
            dbFile.setType(fastDFSUtil.getFileType(file));
            fileMapper.insert(dbFile);
        }
        result.put("普通",url);
        return result;
    }

    /**
     * 获得文件的md5加密
     */
    @Override
    public String getFileMd5(MultipartFile file) throws Exception{
        return MD5Util.getFileMD5(file);
    }

    /**
     * 上传视频封面
     */
    @Override
    public String uploadImg(MultipartFile file, String fileMd5) throws Exception{
        //秒传实现
        QueryWrapper<File> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("md5", fileMd5);
        File dbFile = fileMapper.selectOne(queryWrapper);
        if(dbFile != null){
            return dbFile.getUrl();
        }
        String url = fastDFSUtil.uploadCommonFile(file);
        if(!StringUtils.isNullOrEmpty(url)){
            dbFile = new File();
            dbFile.setCreateTime(new Date());
            dbFile.setUrl(url);
            dbFile.setMd5(fileMd5);
            dbFile.setType(fastDFSUtil.getFileType(file));
            fileMapper.insert(dbFile);
        }

        return url;
    }
}
